<?php
//TODO: perkelti i config ?
define('ROLE_ID_TO_CREATE_USERS', "0"); //Tik admin
class Users extends CI_controller{
    function __construct() {
        parent::__construct();
        $this->config->load('users');
        load_lang_file('users');
    }

    function index(){
        if(!is_logged_in(true)) return;
        $data['iconMenu'] = $this->load->view("admin/iconMenu", array('iconMenuItems' => $this->iconMenu()), TRUE);
        $this->load->view('admin/template', $data);
    }

    function iconMenu(){
        load_lang_file('icons');
        $url = site_url("admin/users").'/';
        $icon_array = null;
        if(user_has_sufficient_role_to('create_new_users')){
            $icon_array[] = array(
                'href' => $url.'create_user',
                'title' => $this->lang->line('create_a_new_user'),
                'img' => 'create_user.png',
                'span_title' => $this->lang->line('create_user')
            );
        }
        $icon_array[] = array(
                'href' => $url.'edit_account',
                'title' => $this->lang->line('edit_my_account'),
                'img' => '16_48x48.png',
                'span_title' => $this->lang->line('edit_account')
            );

        return $icon_array;
    }

    function create_user(){
        if(!is_logged_in(true)) return;
        if(!user_has_sufficient_role_to('create_new_users')){
            $data['iconMenu'] = $this->load->view("admin/iconMenu", array('iconMenuItems' => $this->iconMenu()), TRUE);
            $data['main_content'] = $this->load->view('error', array('error_msg' => $this->lang->line('insufficient_role')), true);
            $data['main_content'] = '<div class="message error"><h2>Error!</h2><p>You don\'t have sufficient role to perform this task</p></div>'; //TODO: multilang
            $this->load->view('admin/template', $data);
            return;
        }

        $data['error_msg'] = null;
        $data['success_msg'] = null;

        if(!empty($_POST)){
            $this->load->library('form_validation');
            $this->form_validation->set_rules('email_address', 'Email Address', 'trim|required|valid_email');
            $this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[4]');
            $this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[4]|max_length[32]');
            $this->form_validation->set_rules('password2', 'Password Confirmation', 'trim|required|matches[password]');

            if($this->form_validation->run() == FALSE){
                    $data['error_msg'] = validation_errors();
            } else {
                $this->load->model('membership_model');
                //Patikriname ar vartotojas tokiu vardu dar neegzistuoja
                if($this->membership_model->member_already_exists()){
                    $data['error_msg'] = "<p>".$this->lang->line('create_user_user_already_exists').
                                "<a href='#'>".//TODO: link to password reminder
                                $this->lang->line('login_password_reminder').
                                "</a></p>";
                    //TODO: password reminder
                } elseif($this->membership_model->email_already_registered()){ //Patikriname ar nurodytas email dar neegzistuoja
                    $data['error_msg'] = "<p>".$this->lang->line('create_user_email_already_registered').
                                "<a href='#'>".//TODO: link to password reminder
                                $this->lang->line('login_password_reminder').
                                "</a></p>";
                    //TODO: password reminder
                } else { //Kuriame nauja vartotoja
                    if($query = $this->membership_model->create_member()){
                        //Pavyko sukurti nauja vartotoja
                        //TODO: send mail for a new user
                        $this->load->library('email');
                        $this->email->from($this->config->item('email_from'), $this->config->item('email_from_title'));
                        $this->email->to($this->input->post('email_address'));
                        $this->email->subject(sprintf($this->lang->line('invitation_mail_subject'), $this->session->userdata('username'), $this->config->item('site_title')));
                        $this->email->message(sprintf($this->lang->line('invitation_mail_content'), $this->session->userdata('username'), $this->config->item('site_title'), base_url()."login", $this->input->post('username'), $this->input->post('password'), $this->session->userdata('username')));
                        $this->email->send();

                        $data['success_msg'] = "<p>".sprintf($this->lang->line('create_user_success'), $this->input->post('username'))."</p>";
                        $_POST = NULL;
                    } else {
                        $data['error_msg'] = "<p>".$this->lang->line('create_user_db_error').$query."</p>";
                    }

                }
            }
        }
        $data['iconMenu'] = $this->load->view("admin/iconMenu", array('iconMenuItems' => $this->iconMenu()), TRUE);
        $data['main_content'] = $this->load->view('admin/create_user_form.php', $data, true);
        $this->load->view('admin/template', $data);
    }

    function edit_account(){
        if(!is_logged_in(true)) return;
        $data['error_msg'] = null;
        $data['success_msg'] = null;
        if(!empty($_POST)){
            $this->load->library('form_validation');
            $this->form_validation->set_rules('email_address', 'Email Address', 'trim|required|valid_email');
            $this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[4]');
            $this->form_validation->set_rules('new_password', 'Password', 'trim|required|min_length[4]|max_length[32]');
            $this->form_validation->set_rules('new_password2', 'Password Confirmation', 'trim|required|matches[new_password]');

            if($this->form_validation->run() == FALSE){
                    $data['error_msg'] = validation_errors();
            } else {
                if(md5($this->input->post('old_password')) == $this->session->userdata('password')){
                     $this->load->model('membership_model');
                     $userId = $this->membership_model->user_id($this->session->userdata('username'));
                    //Patikriname ar vartotojas naujai įvestu vardu dar neegzistuoja
                    if($this->membership_model->member_already_exists(array(0 => $userId))){
                        $data['error_msg'] = "<p>".$this->lang->line('edit_my_account_username_exists')."</p>";
                    } elseif($this->membership_model->email_already_registered(array(0 => $userId))){ //Patikriname ar nurodytas email dar neegzistuoja
                        $data['error_msg'] = "<p>".$this->lang->line('edit_my_account_email_exists')."</p>";
                } else { //Keičiame vartotojo duomenis
                    $this->membership_model->change_user_info($userId, $this->input->post('username'), $this->input->post('email_address'), $this->input->post('new_password'));
                    $data = $this->membership_model->userInfo($this->input->post('username'));
                    $this->session->set_userdata($data);
                    $data['success_msg'] = "<p>".$this->lang->line('edit_my_account_saved')."</p>";
                    $_POST = null;
                }
                } else {
                    $data['error_msg'] = "<p>".$this->lang->line('edit_my_account_incorrect_password')."</p>";
                }
            }
        }
        $data['main_content'] = $this->load->view('admin/edit_user_form.php', $data, true);
        $data['iconMenu'] = $this->load->view("admin/iconMenu", array('iconMenuItems' => $this->iconMenu()), TRUE);
        $this->load->view('admin/template', $data);
    }

}
